package com.cx.repository.impl;


import com.cx.pojo.Comment;
import com.cx.pojo.Responses;
import com.cx.repository.CommentRepository;
import com.mongodb.BasicDBObject;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class CommentRepositoryImpl implements CommentRepository {

    /**
     * 由springboot自动注入，默认配置会产生mongoTemplate这个bean
     */
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public List<JSONObject> findAllComments() {
        Query query = new Query();
        Criteria criteria = Criteria.where("id").exists(false);
        query.addCriteria(criteria);
        List<JSONObject> comments = mongoTemplate.find(query,JSONObject.class);
        for (Object comment:comments) {
            System.out.println(comment.toString());

        }
        return comments;
    }

    @Override
    public List<Comment> findByPostId(String id) {
        Query query = new Query();
        Criteria criteria = Criteria.where("comment_blog_id").is(id);
        query.addCriteria(criteria);
        List<Comment> comments = mongoTemplate.find(query,Comment.class);
        return comments;
    }


    @Override
    public int insertComment(Comment comment) {
        List<Comment> list = new ArrayList<Comment>();
        list.add(comment);
        mongoTemplate.insert(list,Comment.class);
        return 1;
    }

    @Override
    public int deleteComment(String id) {
        Query query = Query.query(Criteria.where("comment_id").is(id));
        mongoTemplate.remove(query,Comment.class);
        return 1;
    }


    @Override
    public int addResponse(String id, Responses responses) {
        Query query = Query.query(Criteria.where("comment_id").is(id));
        Update update = new Update();
        update.addToSet("comment_responses",responses);
        mongoTemplate.upsert(query,update,Comment.class);
        return 1;
    }

    @Override
    public int deleteResponse(String id, String responses_id) {
        Query query = Query.query(Criteria.where("comment_id").is(id));
        BasicDBObject s = new BasicDBObject();
        s.put("id",responses_id);
        Update update = new Update();
        update.pull("comment_responses",s);
        mongoTemplate.updateFirst(query, update, Comment.class);
        return 1;
    }

}
